var express = require('express');
var router = express.Router();
const uuid = require("uuid");
const xlsx = require("node-xlsx");
const path = require("path");
const fs = require("fs");

// 提成集合
const CommissionTemporary = require("../sql/CommissionTemporary");
const Commission = require("../sql/Commission");
// 原始订单集合
const orderSQL = require("../sql/Order");
// 计算提成
const getCommissionData = require("./untils/getCommissionData");

router.get('/', function(req, res, next) {
  const { employeesName } = req.session.userData;
  const date = req.query.month;

  const database = date ? Commission.find({comDate: date.match(/\d+/g).join("")}) : CommissionTemporary.find();

  database.then(async commissionData=>{
    const uData = date ? commissionData[0].comData : await getCommissionData(commissionData);
    res.render('commission', {
      employeesName,
      commissionData: uData,
      index: 4
    });
  }).catch(code=>{
    console.error(code);
    res.send( code );
  })
});

// 保存订单
router.post('/save', function(req, res, next) {
  const date = req.body.month.match(/\d+/g).join("");

  CommissionTemporary.find().then(async commissionData=>{
    const uData = await getCommissionData(commissionData);
    const arr = [];
    uData.forEach(val=>{
      arr.push({
        name: val.name,
        team: Array.isArray(val.team) ? '总经办' : val.team,
        job: val.job,
        count: val.count
      })
    })
    return Commission.find({ comDate: date }).then((data)=>{
      if(data.length > 0){
        return Commission.updateOne( { comDate: date }, { comData: arr } )
      }else{
        return Commission.insertMany( {
          comDate: date,
          comData: arr
        } )
      }
    })
  }).then(()=>{
    res.redirect('/commission');
  }).catch(code=>{
    console.error(code);
    res.redirect('/commission');
  })
});

// 导出提成
router.get('/export', function(req, res, next) {
  let date = req.query.month;
  date = date ? date.match(/\d+/g).join("") : getYM();
  let excelData = [{
    name: "提成数据",
    data:[
      ["姓名", "部门", "职位", "金额", "注意！！！本表不能用作导入！！！"],
    ]
  }];
  res.setHeader('Content-Disposition', 'attachment; filename=commission' + new Date().toLocaleDateString() + Date.now() + '.xlsx');
  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

  try {
    Commission.find({ comDate: date }).then(commissionData=>{
      const uData = commissionData;
      uData[0].comData.forEach(val=>{
        excelData[0].data.push([
          val.name, Array.isArray(val.team) ? '总经办' : val.team, val.job, val.count
        ])
      })
      const buffer = xlsx.build(excelData);
      res.send( buffer );
    }).catch(code=>{
      console.error(code);
      res.send( code );
    })
  } catch (error) {
    console.error(error);
    res.send( error );
  }
});

// 导出模板
router.get('/exportTemp', function(req, res, next) {
  let excelData = [{
    name: "提成数据",
    data:[
      ["*核算号", "*金额", "注意！！！导入时请不要对表结构做任何修改！！！*号为必填"],
    ]
  }];
  const buffer = xlsx.build(excelData);
  res.setHeader('Content-Disposition', 'attachment; filename=commission_template.xlsx');
  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.send( buffer );
});

// 导入订单
router.post('/import', async function(req, res, next) {
  
  const file = req.files[0];
  const xlsxPath = path.join(__dirname, "..", file.path);
  if( file ){
    try {
      // 获取原始订单
      let orderData = await orderSQL.find({}, {_id:0, __v:0})

      const data = xlsx.parse( xlsxPath, { cellDates: true } )[0].data;
      const arr = [];
      for(let i=1; i<data.length; i++){
        if( data[i][0] ){
          arr.push({
            comId: 'commission-'+uuid.v1(), // 唯一标志
            AccountingNo: data[i][0],       // 核算号
            Money: data[i][1]-0 || 0,       // 金额
          })
        }
      }

      // 重复订单号合并金额
      let repeatConcatData = repeatConcat( arr );

      // 删除文件
      fs.unlinkSync( xlsxPath );

      const NothingAccountingNo = [];
      const NothingUser = [];
      // 读取原始订单数据，绑定相关人员
      repeatConcatData.forEach(val=>{
        const oData = orderData.find(v=>v.AccountingNo===val.AccountingNo);
        if(oData){

          // 查看某个订单流程是否为空
          const arr = [ oData.OrderClerk, oData.Marketer, oData.Quoter, oData.Purchasing, oData.Warehouse, oData.ProvideBoat, oData.Financial, oData.Logistics ];
          console.log(arr, val.AccountingNo);
          
          (arr.includes("") || arr.includes(undefined)) && (NothingUser.push( val.AccountingNo ));

          val.OrderClerk = oData.OrderClerk || '';     // 订单员
          val.Marketer = oData.Marketer || '';       // 市场员
          val.Quoter = oData.Quoter || '';        // 报价员
          val.Purchasing = oData.Purchasing || '';    // 采购员
          val.Warehouse = oData.Warehouse || '';     // 仓库员
          val.ProvideBoat = oData.ProvideBoat || '';   // 供船员
          val.Financial = oData.Financial || '';     // 财务员
          val.Logistics = oData.Logistics || '';     // 物流员
        }else{
          NothingAccountingNo.push( val.AccountingNo );
        }
      })

      if(NothingAccountingNo.length < 1 && NothingUser.length < 1){
        // 删除历史数据
        await CommissionTemporary.deleteMany( {} );
        // 插入新数据
        await CommissionTemporary.insertMany( repeatConcatData )
        res.redirect("/commission");
      }else{
        res.send({
          msg:`提成计算失败！以下【NothingAccountingNo】核算号在原始订单【订单管理】中不存在，以下【NothingUser】核算号在原始订单【订单管理】中某个流程无人认领，请检查后处理后，重新计算提成`, 
          NothingAccountingNo: NothingAccountingNo,
          NothingUser: NothingUser
        });
      }

    } catch (error) {
      console.error( error );
      fs.unlink( xlsxPath, ()=>{
        res.redirect('/commission');
      } )
    }
  }else{
    fs.unlink( xlsxPath, ()=>{
      res.redirect('/commission');
    } )
  }
});

function repeatConcat( data ){
  const arr = [];
  data.forEach(val=>{
    if(arr.find(v=>v.AccountingNo===val.AccountingNo)){
      const index = arr.findIndex(v=>v.AccountingNo===val.AccountingNo);
      arr[index].Money = ((arr[index].Money-0) + (val.Money-0)).toFixed(2)-0;
    }else{
      arr.push( val );
    }
  })
  return arr;
}

function getYM(){
  const d = new Date();
  return "" + d.getFullYear() + cz(d.getMonth()+1)
}

function cz(n){
  return n < 10 ? "0"+n : n;
}

module.exports = router;
